package xfuzzy.alg_genetico.indeterminado.database;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ChromosomeDatabase {
	
	private Connection conn;
	
	private synchronized void openConnection() throws SQLException, ClassNotFoundException  {
		
		Class.forName("org.sqlite.JDBC");
		String ruta = "chromosome.db";
		
		if (!new File(ruta).exists())  {
			conn = DriverManager.getConnection("jdbc:sqlite:" + ruta);
			Statement stat = conn.createStatement();
	        stat.executeUpdate("create table CHROMOSOME (codification VARCHAR(255), fitness VARCHAR(255));");
		}
		
		this.conn = DriverManager.getConnection("jdbc:sqlite:" + ruta);
	}
	
	private synchronized void closeConnection() throws SQLException {
		
		this.conn.close();
	}
	
	public synchronized boolean saveCodification(String codification, Double fitness)  {
		
		//if (this.getFitness(codification) != null)  {
			try  {
				//if (this.getFitness(codification) != null)  {
					this.openConnection();
					PreparedStatement prep = this.conn.prepareStatement("insert into CHROMOSOME values (?, ?);");
			        prep.setString(1, codification);
			        prep.setString(2, String.valueOf(fitness));
			        prep.executeUpdate();
			        this.closeConnection();
			        return true;
				//}
			}
			catch(Exception e)  {
				System.out.println(e.getMessage());
				e.printStackTrace();
				return false;
			}
		//}
	}
	
	public synchronized Double getFitness(String codification)  {
		
		Double value = null;
		try  {
			this.openConnection();
			Statement stat = this.conn.createStatement();
			ResultSet rs = stat.executeQuery("SELECT * from CHROMOSOME where codification = '" + codification + "';");
			if (rs.next())  {
				value = new Double(Double.valueOf(rs.getString(2)));
			}
			else  {
				value = Double.MAX_VALUE;
			}
			this.closeConnection();
		}
		catch(Exception e)  {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return value;
	}
}
